package top.ahzy.seobench.sparkLite;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.jetbrains.annotations.NotNull;
import top.ahzy.seobench.consts.MessageSocketConst;
import top.ahzy.seobench.model.dto.MessageDto;
import top.ahzy.seobench.sparkLite.model.RoleContent;
import top.ahzy.seobench.sparkLite.model.SparkModel;
import top.ahzy.seobench.websocket.MessageSocket;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import java.util.TimeZone;

@Data
@EqualsAndHashCode(callSuper = true)
@Slf4j
public class SparkWebSocket extends WebSocketListener {

    private String token;

    private final MessageSocket messageSocket;

    public SparkWebSocket(MessageSocket messageSocket) {
        this.messageSocket = messageSocket;
    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
        log.info("响应:{}", text);
        JSONObject res = new JSONObject(text);
        for (Object o : res.getJSONObject("payload").getJSONObject("choices").getJSONArray("text")) {
            SparkService.sparkWebSocketMap.get(token).getTotalAnswer().append(JSONUtil.parseObj(o).getStr("content"));

            // 给用户发信息
            MessageDto msg = new MessageDto();
            msg.setType(MessageSocketConst.MESSAGE_TYPE_SPARK);
            msg.setComsumerId(token);
            msg.setUserId(MessageSocketConst.MESSAGE_TYPE_SPARK);
            msg.setContent(JSONUtil.parseObj(o).getStr("content"));
            messageSocket.sendMsg(msg);
        }

        String status = res.getJSONObject("payload").getJSONObject("choices").getStr("status");
        if ("2".equals(status)) {
            RoleContent roleContent = new RoleContent();
            roleContent.setRole("assistant");
            roleContent.setContent(SparkService.sparkWebSocketMap.get(token).getTotalAnswer().toString());
            SparkService.sparkWebSocketMap.get(token).getHistoryList().add(roleContent);
            SparkService.sparkWebSocketMap.get(token).setTotalAnswer(new StringBuffer());
            webSocket.close(1000, "");

            MessageDto msg = new MessageDto();
            msg.setType(MessageSocketConst.MESSAGE_TYPE_SPARK);
            msg.setComsumerId(token);
            msg.setContent(MessageSocketConst.MESSAGE_TYPE_SPARK);
            messageSocket.sendMsg(msg);
        }


    }

    public void send(SparkModel sparkModel, String context) throws Exception {
        JSONObject contextJson = new JSONObject(context);
        // 最新问题
        RoleContent userRoleContent = new RoleContent();
        userRoleContent.setRole("user");
        userRoleContent.setContent(JSONUtil.parseObj(contextJson.getJSONObject("payload").getJSONObject("message").getJSONArray("text").get(0)).getStr("content"));
        if (CollUtil.isEmpty(sparkModel.getHistoryList())) {
            sparkModel.setHistoryList(new ArrayList<>());
        }
        sparkModel.getHistoryList().add(userRoleContent);

        // 构建鉴权url
        String authUrl = this.getAuthUrl(SparkConst.hostUrl, SparkConst.apiKey, SparkConst.apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
        SparkWebSocket sparkWebSocket = new SparkWebSocket(messageSocket);
        sparkWebSocket.setToken(token);
        WebSocket webSocket = client.newWebSocket(request, sparkWebSocket);
        System.out.println("send:" + context);
        webSocket.send(context);
    }

    public String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build();

        return httpUrl.toString();
    }


}
